package com.ego.item.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ego.common.pojo.PageResult;
import com.ego.exception.enums.ExceptionEnum;
import com.ego.exception.exception.EgoException;
import com.ego.item.entity.Brand;
import com.ego.item.mapper.BrandMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class BrandService {
    @Resource
    private BrandMapper brandMapper;
    public PageResult<Brand> queryBrandByPageAndSort(Integer page, Integer pageSize, String sortBy, Boolean desc, String key) {
        QueryWrapper<Brand> brandQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(key)){
            brandQueryWrapper.like("name",key)
                    .or()
                    .eq("letter",key);

        }if (StringUtils.isNotBlank(sortBy)){
            brandQueryWrapper.orderBy(StringUtils.isNotBlank(sortBy),desc,sortBy);
            // 查询
        }
        Page<Brand> pageInfo = brandMapper.selectPage(new Page<>(page, pageSize), brandQueryWrapper);
        // 返回结果
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getRecords());
    }
    @Transactional
    public void save(Brand brand, Long[] cids) {
    brandMapper.insert(brand);
        for (Long cid:cids) {
            brandMapper.insertCategoryAndBrand(cid,brand.getId());
        }

    }
    @Transactional
    public void update(Brand brand, Long[] cids) {
        brandMapper.updateById(brand);
        brandMapper.deleteCategoryAndBrand(brand.getId());
        for (Long cid:cids) {
            brandMapper.insertCategoryAndBrand(cid,brand.getId());
        }
    }
    @Transactional
    public void delete(Long id) {
        brandMapper.deleteBrand(id);
        brandMapper.deleteCategoryAndBrand(id);
    }

    @Transactional(readOnly = true)
    public List<Brand> queryById(Integer cid) {
        List<Brand> result = null;
        try {
            result  = brandMapper.selectListByCid(cid);
        }catch (Exception e){
            EgoException.error(log, ExceptionEnum.BRAND_NOT_FOUND,e);
        }
        return result;
    }
    @Transactional(readOnly = true)
    public List<Brand> queryBrandByIds(List<Long> ids) {
        return this.brandMapper.selectBatchIds(ids);
    }
}
